
const gulp = require("gulp");
const ts = require("gulp-typescript");
const sourcemaps = require('gulp-sourcemaps');
const rename = require("gulp-rename");
const uglify = require("gulp-uglify");
const concat = require('gulp-concat');
const clean = require('gulp-clean');
const jsobfuscator = require('gulp-javascript-obfuscator');
const debug = require('gulp-debug');
const notify = require('gulp-notify');
const merge = require('merge2');
const through = require('through2');
const fs = require("fs");
const path = require("path");
const yargs = require('yargs');

/**
 * 清空包声明
 */
function cleanDeclaration(cb) {
	let argv = yargs.default('pack', 'main').argv;
	let pack = argv.pack;
	console.log("cleanDeclaration " + pack);
	return gulp.src([ '../../@types/packs/' + pack + '.d.ts' ], { read: false, allowEmpty:true })
		.pipe(clean({ force:true }));
}

/**
 * 构建包声明
 */
function buildDeclaration(cb) {
	let argv = yargs.default('pack', 'main').argv;
	let pack = argv.pack;
	let sources = null;
	if(pack == "main"){
		sources = gulp.src([ '../../@types/**/*.ts', '../../assets/**/*.ts', '!../../assets/packs/**/*.ts', '../../temp/declarations/**/*.ts' ]);
	}else{
		sources = gulp.src([ '../../@types/**/*.ts', '../../assets/packs/' + pack + '/**/*.ts', '../../temp/declarations/**/*.ts' ]);
	}
	console.log("buildDeclaration " + pack);
	//let filecount:{[key:string]:number} = {};
	let tsResult = sources.pipe(ts.createProject({
		module : "commonjs",
		target : "ES2015",
		experimentalDecorators : true,
		skipLibCheck : true,
		noImplicitAny : false,
		declaration : true,
		removeComments : false,
	})())
	.on("error",function(err:any){
		console.error(err.message);
	});
	return tsResult.dts
		/*
		.pipe(through.obj(function (chunk, enc, callback){
			let basename = path.basename(chunk.path, ".d.ts")
			let count = filecount[basename] || 0;
			filecount[basename] = count + 1;
			if(count > 0){
				basename = basename + "_" + count;
			}
			let sdata = chunk.contents.toString();
			sdata = "declare module " + basename + "{\n" + sdata + "\n}\n";
			chunk.contents = Buffer.from(sdata);
			this.push(chunk)
			callback();
		}))
		*/
		.pipe(concat(pack + ".d.ts"))
		.pipe(through.obj(function (chunk, enc, callback){
			let sdata = chunk.contents.toString();
			sdata = `// generate by lcc-framework\n\ndeclare namespace lcc$PACKS.${pack} {\n\n${sdata.replace(/([ \t]+(default|declare)[ \t]+)+/g, " ")}\n\n}`;
			chunk.contents = Buffer.from(sdata);
			this.push(chunk)
			callback();
		}))
		.pipe(gulp.dest("../../@types/packs"));
}

export const build = gulp.series(cleanDeclaration, buildDeclaration);
